﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
using System.Threading;
using Newtonsoft.Json;
using System.Runtime.InteropServices.ComTypes;
using System.Diagnostics;
using System.Linq.Expressions;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
//using System.Threading.Tasks;

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CreateParamsList();
        }
        public static string str;
        public static string Str { get { return str; } set { str = value; Form1 form = new Form1();  form.reqTxt.Text = value; } }

        private void Form1_Load(object sender, EventArgs e)
        {
            reqType.SelectedIndex = 0;
        }
        static int count = 1;
        static int scount = 1;
        static int state = 0;
        public static Dictionary<int,List<ReqLog>> reqDic= new Dictionary<int, List<ReqLog>>();
        private void button1_Click(object sender, EventArgs e)
        {
            if (state==0)
            {
                count = 1;
                scount = int.Parse(textBox1.Text);
                if (scount <= 0)
                {
                    MessageBox.Show("请输入大于0的请求次数");
                    return;
                }
                requestRecord.Rows.Clear();
                if (int.Parse(textBox2.Text) > 1)//线程大于一
                {
                    allState = true;
                    ThreadsReq();
                    return;
                }
                button1.Text = "点击停止";
                state = 1;
                textBox1.Enabled = false;


                Stopwatch sw = new Stopwatch();
                sw.Start();
                while (count <= scount)
                {
                    if (rWebServer.Checked)
                    {
                        WebService(false);
                    }
                    else
                    {
                        WebApi(false);
                    }
                    Application.DoEvents();
                    textBox1.Text = (count++).ToString();
                }
                sw.Stop();
                label15.Text= "总耗时：" + $"{sw.Elapsed.Hours}时{sw.Elapsed.Minutes}分{sw.Elapsed.Seconds}秒{sw.Elapsed.Milliseconds}毫秒";
                count = 1;
                button1.Text = "发送请求";
                state = 0;
                textBox1.Enabled = true;
                textBox1.Text=scount.ToString();
            }
            else
            {
                count = scount;
                button1.Text = "发送请求";
                state = 0;
                textBox1.Enabled = true;
                textBox1.Text = scount.ToString();
            }
        }
        public void ThreadsReq()
        {
            dataGridView1.Rows.Clear();
            reqDic.Clear();
            int count = 0;
            bool isw = true;
            int rCount = int.Parse(textBox2.Text);
            while (count < rCount)
            {
                dataGridView1.Rows.Add(count, 0,"运行中");
                Thread.Sleep(10);
                reqDic.Add(count, new List<ReqLog>());
                Thread thread=new Thread(() =>
                {
                    int taskId = count;
                    isw = false;
                    int req = 0;//请求的次数
                    int reqcount = 0;
                    bool iswebserver = false;
                    bool isready = false;
                    int SelectedIndex = 0;
                    string url = "";
                    string reqs = "";
                    this.BeginInvoke((MethodInvoker)delegate
                    {
                        reqcount = int.Parse(textBox1.Text);//需要请求的次数
                        if (rWebServer.Checked)
                            iswebserver = true;
                        SelectedIndex = comboBox1.SelectedIndex;
                        url = urlTxt.Text;
                        if (SelectedIndex == 0)
                        {
                            bool isone = false;
                            Dictionary<string, string> map = new Dictionary<string, string>();
                            for (int i = 0; i < paraPanel.Controls.Count; i += 2)
                            {
                                if (paraPanel.Controls[i].Text == "" && paraPanel.Controls[i + 1].Text != "")
                                {
                                    isone = true;
                                    reqs = paraPanel.Controls[i + 1].Text;
                                    break;
                                }
                                if (paraPanel.Controls[i].Text == "")
                                {
                                    continue;
                                }
                                map.Add(paraPanel.Controls[i].Text, paraPanel.Controls[i + 1].Text);
                            }
                            if (!isone)
                            {
                                reqs = map.Count > 0 ? JsonConvert.SerializeObject(map) : "";
                            }
                        }
                        else
                        {
                            for (int i = 0; i < paraPanel.Controls.Count; i += 2)
                            {
                                if (paraPanel.Controls[i].Text == "")
                                {
                                    continue;
                                }
                                reqs += "&" + paraPanel.Controls[i].Text + "=" + paraPanel.Controls[i + 1].Text;
                            }
                        }
                        dataGridView1.Rows[taskId].Cells[2].Value = "配置完参数，开始请求";
                        //dataGridView1.Rows[taskId].Cells[1].Value = sw.ElapsedMilliseconds / 1000;
                        isready = true;
                    });
                    while (!isready)
                    {

                    }
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    while (req < reqcount && allState)
                    {
                        Stopwatch swr = new Stopwatch();
                        swr.Reset();
                        swr.Start();
                        string msg = "";
                        if (iswebserver)
                        {
                            msg=WebService(true);
                        }
                        else
                        {
                            msg=WebApiThread(SelectedIndex, url, reqs);
                        }
                        //Thread.Sleep(taskId);
                        req++;
                        reqDic[taskId].Add(new ReqLog { time = swr.ElapsedMilliseconds, msg = msg });
                        //MessageBox.Show(taskId.ToString());
                        //dataGridView1.Rows[taskId].Cells[1].Value = req;
                    }
                    sw.Stop();
                    //SetDGv(taskId, sw);
                    this.BeginInvoke((MethodInvoker)delegate
                    {
                        dataGridView1.Rows[taskId].Cells[2].Value = "完成";
                        dataGridView1.Rows[taskId].Cells[1].Value = sw.ElapsedMilliseconds / 1000 + "s";
                    });
                });
                thread.Start();
                //Task.Run(() =>
                //{

                //});
                while (isw)
                {

                }
                count++;
                isw = true;
            }
        }
        public void SetDGv(int taskId, Stopwatch sw)
        {
            dataGridView1.Rows[taskId].Cells[2].Value = "完成";
            dataGridView1.Rows[taskId].Cells[1].Value = sw.ElapsedMilliseconds / 1000;
        }
        bool allState=false;
        private void button6_Click(object sender, EventArgs e)
        {
            allState = false;
        }
        public string WebService(bool isThread)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(LaborderlistClass));
            if (urlTxt.Text == "" || actionTxt.Text == "" || nodeNameTxt.Text == "")
            {
                MessageBox.Show("除了命名空间，其他全部必填");
                return null;
            }
            //string req = $@"<cid>{parameterTxt}<cid>";
            Dictionary<string, string> map = new Dictionary<string, string>();
            for (int i = 0; i < paraPanel.Controls.Count; i += 2)
            {
                //map.Add(paraPanel.Controls[i].Text,HttpUtility.HtmlEncode(paraPanel.Controls[i + 1].Text));
                map.Add(paraPanel.Controls[i].Text, $"<![CDATA[{paraPanel.Controls[i + 1].Text}]]>");
            }
            string res = "";
            try
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();
                if (!isThread)
                {
                    label11.Text = "开始时间：" + DateTime.Now.ToString("HH:mm:ss fff");
                    res = SOAPWebService(urlTxt.Text, map, actionTxt.Text, nodeNameTxt.Text, nameSpaceTxt.Text);
                    label12.Text = "结束时间：" + DateTime.Now.ToString("HH:mm:ss fff");
                    sw.Stop();
                    label13.Text = "耗时：" + $"{sw.Elapsed.Hours}时{sw.Elapsed.Minutes}分{sw.Elapsed.Seconds}秒{sw.Elapsed.Milliseconds}毫秒";
                    requestRecord.Rows.Add(count, label11.Text.Substring(5), label12.Text.Substring(5), label13.Text.Substring(3));
                }
                else
                {
                    res = SOAPWebService(urlTxt.Text, map, actionTxt.Text, nodeNameTxt.Text, nameSpaceTxt.Text);
                }
                sw.Reset();
            }
            catch (Exception ex)
            {
                resTxt.Text = ex.Message+ex.StackTrace;
                return null;
            }


            //XmlDocument xml = new XmlDocument();
            //xml.LoadXml(res);
            //XmlNamespaceManager xmlNamespace = new XmlNamespaceManager(xml.NameTable);
            //xmlNamespace.AddNamespace("ns", "http://tempuri.org/");
            //XmlNode node = xml.DocumentElement.SelectSingleNode("//ns:Medsoon", xmlNamespace);

            //XmlNode no = xml.DocumentElement.SelectSingleNode("//Medsoon");
            ////序列化后的值
            //LaborderlistClass laborderlist = XmlStrToObject<LaborderlistClass>(node.InnerXml);
            if (!isThread)
                getNode.Text = res;
            return res;
        }
        public void WebApi(bool isThread)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(LaborderlistClass));
            if (urlTxt.Text == "")
            {
                MessageBox.Show("Url必填");
                return;
            }
            if (comboBox1.SelectedIndex == 0)
            {
                //string req = $@"<cid>{parameterTxt}<cid>";
                Dictionary<string, string> map = new Dictionary<string, string>();
                bool isone = false;
                string req = "";
                for (int i = 0; i < paraPanel.Controls.Count; i += 2)
                {
                    if (paraPanel.Controls[i].Text == "" && paraPanel.Controls[i + 1].Text != "")
                    {
                        isone = true;
                        req = JsonConvert.SerializeObject(paraPanel.Controls[i + 1].Text);
                        break;
                    }
                    if (paraPanel.Controls[i].Text == "")
                    {
                        continue;
                    }
                    map.Add(paraPanel.Controls[i].Text, paraPanel.Controls[i + 1].Text);
                }
                if (!isone)
                {
                    req = map.Count > 0 ? JsonConvert.SerializeObject(map) : "";
                }
                if (!isThread)
                    reqTxt.Text = req;
                string res = "";
                try
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    
                    if (!isThread)
                    {
                        label11.Text = "开始时间：" + DateTime.Now.ToString("HH:mm:ss fff");
                        Dictionary<string,string> token=new Dictionary<string,string>();
                        if (txtTokenName.Text!="")
                        {
                            token.Add(txtTokenName.Text, txtToken.Text);
                        }
                        res = HttpPost(urlTxt.Text, req, cbcontentType.Text, 10, token.Count>0?token:null).Result;
                        label12.Text = "结束时间：" + DateTime.Now.ToString("HH:mm:ss fff");
                        sw.Stop();
                        label13.Text = "耗时：" + $"{sw.Elapsed.Hours}时{sw.Elapsed.Minutes}分{sw.Elapsed.Seconds}秒{sw.Elapsed.Milliseconds}毫秒";
                        requestRecord.Rows.Add(count, label11.Text.Substring(5), label12.Text.Substring(5), label13.Text.Substring(3));
                    }
                    else
                    {
                        Dictionary<string, string> token = new Dictionary<string, string>();
                        if (txtTokenName.Text != "")
                        {
                            token.Add(txtTokenName.Text, txtToken.Text);
                        }
                        res = HttpPost(urlTxt.Text, req, cbcontentType.Text, 10, token.Count > 0 ? token : null).Result;
                        //res = HttpPost(urlTxt.Text, req, txtToken.Text);
                    }
                    sw.Reset();
                }
                catch (Exception ex)
                {
                    res = ex.Message;
                }
                if (!isThread)
                    resTxt.Text = res;
            }
            else
            {
                //string req = $@"<cid>{parameterTxt}<cid>";
                string req = "";
                for (int i = 0; i < paraPanel.Controls.Count; i += 2)
                {
                    if (paraPanel.Controls[i].Text == "")
                    {
                        continue;
                    }
                    req += "&" + paraPanel.Controls[i].Text + "=" + paraPanel.Controls[i + 1].Text;
                }
                if (!isThread)
                    reqTxt.Text = urlTxt.Text + (req == "" ? "" : ("?" + req.Substring(1)));
                string res = "";
                try
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    if (!isThread)
                    {
                        label11.Text = "开始时间：" + DateTime.Now.ToString("HH:mm:ss fff");
                        res = HttpGet(urlTxt.Text + (req == "" ? "" : ("?" + req.Substring(1))),4000, txtToken.Text);
                        label12.Text = "结束时间：" + DateTime.Now.ToString("HH:mm:ss fff");
                        sw.Stop();
                        label13.Text = "耗时：" + $"{sw.Elapsed.Hours}时{sw.Elapsed.Minutes}分{sw.Elapsed.Seconds}秒{sw.Elapsed.Milliseconds}毫秒";
                        requestRecord.Rows.Add(count, label11.Text.Substring(5), label12.Text.Substring(5), label13.Text.Substring(3));
                    }
                    else
                    {
                        res = HttpGet(urlTxt.Text + (req == "" ? "" : ("?" + req.Substring(1))), 4000, txtToken.Text);
                    }
                    sw.Reset();
                }
                catch (Exception ex)
                {
                    res = ex.Message;
                }
                if (!isThread)
                    resTxt.Text = res;
            }
        }
        public string WebApiThread(int SelectedIndex,string url,string req)
        {
            if (SelectedIndex == 0) 
            {
                try
                {
                    Dictionary<string, string> token = new Dictionary<string, string>();
                    if (txtTokenName.Text != "")
                    {
                        token.Add(txtTokenName.Text, txtToken.Text);
                    }
                    return HttpPost(urlTxt.Text, req, cbcontentType.Text, 10, token.Count > 0 ? token : null).Result; ;
                    //return HttpPost(url, req, txtToken.Text);
                }
                catch (Exception)
                {
                    return null;
                }
            }
            else
            {
                try
                {
                    //MessageBox.Show();
                    return HttpGet(url + (req == "" ? "" : ("?" + req.Substring(1))), 4000, txtToken.Text);
                }
                catch (Exception)
                {
                    return null;
                }
            }
        }
        public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            //直接确认，否则打不开
            return true;
        }
        /// <summary>
        /// SOAP请求
        /// </summary>
        /// <param name="url">接口地址（不需要带方法名）</param>
        /// <param name="request">请求参数Dictionary<string,string>第一个参数名第二个值</param>
        /// <param name="soapAction">soapAction</param>
        /// <param name="nodeName">需要获取的节点</param>
        /// <param name="nameSpace">命名空间</param>
        /// <param name="time">请求超时时间</param>
        /// <returns></returns>
        public string SOAPWebService(string url, Dictionary<string,string> request, string soapAction, string nodeName, string nameSpace = "http://tempuri.org/", int time = 4000)
        {
            try
            {
                if (request.Count == 0)
                    return null;
                string method = soapAction.Substring(soapAction.LastIndexOf("/") + 1);
                StringBuilder sb = new StringBuilder();
                foreach (var item in request)
                {
                    sb.AppendLine($"<{item.Key}>{item.Value}</{item.Key}>");
                }
                string req = $@"<?xml version=""1.0"" encoding=""utf-8""?>
                                <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
                                    <soap:Body>
                                        <{method} xmlns=""{nameSpace}"">
                                            {sb.ToString()}
                                        </{method}>
                                    </soap:Body>
                                </soap:Envelope>";
                reqTxt.Text = req;
                var webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.Headers.Add("SOAPAction", soapAction);
                webRequest.ContentType = "text/xml;charset=\"utf-8\"";//"text/xml;charset=\"utf-8\"";
                webRequest.Timeout = time;
                webRequest.Accept = "text/xml";//"text/xml";
                webRequest.Method = "POST";
                //string req = request;
                Stream RequestStream = webRequest.GetRequestStream();
                byte[] bytes = Encoding.UTF8.GetBytes(req);
                RequestStream.Write(bytes, 0, bytes.Length);
                RequestStream.Close();

                //接收证书进行身份验证
                ServicePointManager.ServerCertificateValidationCallback =
                    new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
                //todo：指定请求包的安全协议
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                HttpWebResponse response;
                try
                {
                    response = (HttpWebResponse)webRequest.GetResponse();
                }
                catch (WebException ex)
                {
                    response = (HttpWebResponse)ex.Response;
                }
                //StreamReader myStreamReader = new StreamReader(response.GetResponseStream());
                //string result1 = myStreamReader.ReadToEnd();
                //myStreamReader.Close();
                //response.Close();
                //MessageBox.Show(result1);
                //return result1;


                Stream ResponseStream = response.GetResponseStream();
                //原始数据
                //StreamReader sr = new StreamReader(ResponseStream, Encoding.UTF8);
                //string result1 = HttpUtility.HtmlDecode(sr.ReadToEnd());
                //dResTxt.Text = result1;

                //处理多余的<?xml>
                StreamReader reader = new StreamReader(ResponseStream);
                string str = HttpUtility.HtmlDecode(reader.ReadToEnd());
                dResTxt.Text = str;
                string[] arr = str.Split(new string[] { "<?xml" }, StringSplitOptions.RemoveEmptyEntries);
                int len2 = arr.Length;//<?xml的个数
                string strRemoveXml = "";
                if (len2>1)
                {
                    for (int i = 0; i < len2 - 1; i++)
                    {
                        int lastt = str.LastIndexOf("<?xml");
                        int lastb = str.LastIndexOf("?>");
                        string strr = str.Substring(lastt, lastb - lastt + 2);
                        strRemoveXml = str.Replace(strr, "");
                    }
                }
                else
                {
                    strRemoveXml = str;
                }
                byte[] array = Encoding.UTF8.GetBytes(strRemoveXml);
                MemoryStream stream = new MemoryStream(array);

                //去掉非数据节点
                XmlTextReader Reader = new XmlTextReader(stream);
                Reader.MoveToContent();
                string result = HttpUtility.HtmlDecode(Reader.ReadInnerXml());
                resTxt.Text = result;
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(result);
                XmlNode node = null;
                if (nameSpace == "")
                {
                    node = xml.DocumentElement.SelectSingleNode($"//{nodeName}");
                }
                else
                {
                    XmlNamespaceManager xmlNamespace = new XmlNamespaceManager(xml.NameTable);
                    xmlNamespace.AddNamespace("ns", nameSpace);
                    node = xml.DocumentElement.SelectSingleNode($"//ns:{nodeName}", xmlNamespace);
                }
                return node?.InnerXml;
            }
            catch (Exception ex)
            {
                //HttpWebResponse res = (HttpWebResponse)ex.Response;
                //StreamReader sr = new StreamReader(res.GetResponseStream());
                //string strHtml = sr.ReadToEnd();
                resTxt.Text = ex.Message + ex.StackTrace;// + "\r\n\r\n\r\n========\r\n" + strHtml
                return null;
            }
            //catch (WebException ex)
            //{

            //}
            
        }
        public static T XmlStrToObject<T>(string xmlStr) where T : class
        {
            if (string.IsNullOrEmpty(xmlStr)) return null;

            try
            {
                using (StringReader sr = new StringReader(xmlStr))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return serializer.Deserialize(sr) as T;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private Mutex mutex = new Mutex();
        private async Task<string> HttpPost(string url, object postData = null, string contentType = "application/json", int timeOut = 10, Dictionary<string, string> headers = null)
        {
            try
            {
                //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                //request.Timeout = 10000;
                //request.Method = "POST";
                //request.Accept = "text/html";
                //request.ContentType = "application/json";
                //Encoding encoding = Encoding.UTF8;
                //byte[] buffer = encoding.GetBytes(body);
                //request.ContentLength = buffer.Length;
                //request.GetRequestStream().Write(buffer, 0, buffer.Length);
                //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                //{
                //    return reader.ReadToEnd();
                //}
                //System.Net.ServicePointManager.Expect100Continue = true;
                //System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls;
                //HttpClientHandler handler = new HttpClientHandler();
                //handler.AllowAutoRedirect = true;
                //handler.UseCookies = true;


                //System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

                //var handler = new HttpClientHandler();
                //handler.ServerCertificateCustomValidationCallback = delegate { return true; };


                var handler = new HttpClientHandler()
                {
                    UseCookies = false, //设置为false，登陆后重定向的话不会自动带上cookies，需要手动给headers上加入cookies.
                    AllowAutoRedirect = true
                };
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
                //hander.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
                System.Net.ServicePointManager.ServerCertificateValidationCallback = (message, cert, chain, errors) =>
                {
                    // 在这里添加你的证书验证逻辑
                    // 例如，永远返回true来允许所有证书（不推荐用于生产环境）
                    return true;
                };

                postData = postData ?? "";
                HttpClient client = new HttpClient(handler);
                client.Timeout = new TimeSpan(0, 0, timeOut);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                if (contentType == "application/json")
                {
                    HttpContent httpContent = new StringContent(postData.ToString(), Encoding.UTF8);
                    if (contentType != null)
                        httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                    HttpResponseMessage response = await client.PostAsync(url, httpContent).ConfigureAwait(false);
                    return await response.Content.ReadAsStringAsync();
                }
                else
                {
                    var formDataContent = new MultipartFormDataContent();
                    formDataContent.Headers.Add("ContentType", "multipart/form-data");//声明头部

                    if (postData != null)
                    {
                        Dictionary<string, string> postDatas = JsonConvert.DeserializeObject<Dictionary<string, string>>(postData.ToString());
                        foreach (var data in postDatas)
                            formDataContent.Add(new System.Net.Http.StringContent(data.Value), data.Key);
                    }
                    HttpResponseMessage response = await client.PostAsync(url, formDataContent).ConfigureAwait(false);
                    return await response.Content.ReadAsStringAsync();
                }

            }
            catch (Exception ex)
            {
                //string s = ex.Message.ToString();
                return "{\"Code\":\"404\",\"Msg\":\"" + ex.Message + "，请联系工作人员检查网线是否正常\",\"Data\":\"\"}";
            }

        }
        private async Task<string> HttpGetRow(string url, object postData = null, string contentType = "application/json", int timeOut = 10, Dictionary<string, string> headers = null)
        {
            try
            {

                var handler = new HttpClientHandler()
                {
                    UseCookies = false, //设置为false，登陆后重定向的话不会自动带上cookies，需要手动给headers上加入cookies.
                    AllowAutoRedirect = true
                };
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
                //hander.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
                System.Net.ServicePointManager.ServerCertificateValidationCallback = (message, cert, chain, errors) =>
                {
                    // 在这里添加你的证书验证逻辑
                    // 例如，永远返回true来允许所有证书（不推荐用于生产环境）
                    return true;
                };

                postData = postData ?? "";
                HttpClient client = new HttpClient(handler);
                client.Timeout = new TimeSpan(0, 0, timeOut);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                if (contentType == "application/json")
                {
                    HttpContent httpContent = new StringContent(postData.ToString(), Encoding.UTF8);
                    if (contentType != null)
                        httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                    HttpResponseMessage response = await client.PostAsync(url, httpContent).ConfigureAwait(false);
                    return await response.Content.ReadAsStringAsync();
                }
                else
                {
                    var formDataContent = new MultipartFormDataContent();
                    formDataContent.Headers.Add("ContentType", "multipart/form-data");//声明头部

                    if (postData != null)
                    {
                        Dictionary<string, string> postDatas = JsonConvert.DeserializeObject<Dictionary<string, string>>(postData.ToString());
                        foreach (var data in postDatas)
                            formDataContent.Add(new System.Net.Http.StringContent(data.Value), data.Key);
                    }
                    HttpResponseMessage response = await client.PostAsync(url, formDataContent).ConfigureAwait(false);
                    return await response.Content.ReadAsStringAsync();
                }

            }
            catch (Exception ex)
            {
                //string s = ex.Message.ToString();
                return "{\"Code\":\"404\",\"Msg\":\"" + ex.Message + "，请联系工作人员检查网线是否正常\",\"Data\":\"\"}";
            }

        }
        private async Task<string> HttpPostFormData(string url, Dictionary<string,string> postDatas =null, string contentType = "multipart/form-data", int timeOut = 10, Dictionary<string, string> headers = null)
        {
            try
            {
                var handler = new HttpClientHandler()
                {
                    UseCookies = false, //设置为false，登陆后重定向的话不会自动带上cookies，需要手动给headers上加入cookies.
                    AllowAutoRedirect = true
                };
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
                //hander.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
                System.Net.ServicePointManager.ServerCertificateValidationCallback = (message, cert, chain, errors) =>
                {
                    // 在这里添加你的证书验证逻辑
                    // 例如，永远返回true来允许所有证书（不推荐用于生产环境）
                    return true;
                };

                //postData = postData ?? "";
                HttpClient client = new HttpClient(handler);

                var formDataContent = new MultipartFormDataContent();
                formDataContent.Headers.Add("ContentType", "multipart/form-data");//声明头部
                if (postDatas != null)
                {
                    foreach (var postData in postDatas)
                        formDataContent.Add(new System.Net.Http.StringContent(postData.Key), postData.Value);
                }
                //formDataContent.Add(new System.Net.Http.StringContent("aa"), "");


                client.Timeout = new TimeSpan(0, 0, timeOut);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                //HttpContent httpContent = new StringContent(postData, Encoding.UTF8);
                //if (contentType != null)
                //    httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                HttpResponseMessage response = await client.PostAsync(url, formDataContent).ConfigureAwait(false);
                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                //string s = ex.Message.ToString();
                return "{\"Code\":\"404\",\"Msg\":\"" + ex.Message + "，请联系工作人员检查网线是否正常\",\"Data\":\"\"}";
            }

        }

        //private string HttpPost(string url, string body, string token = "")
        //{
        //    try
        //    {
        //        //mutex.WaitOne();
        //        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        //        request.Timeout = 10000;
        //        request.Method = "POST";
        //        //request.Accept = "application/json";
        //        request.ContentType = "application/json";
        //        if (token != "")
        //        {
        //            //request.Headers.Add("Authorization", "Bearer " + token);
        //            request.Headers.Add(txtTokenName.Text, token);
        //        }
        //        Encoding encoding = Encoding.UTF8;
        //        byte[] buffer = encoding.GetBytes(body);
        //        request.ContentLength = buffer.Length;
        //        request.GetRequestStream().Write(buffer, 0, buffer.Length);

        //        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        //        using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
        //        {
        //            return reader.ReadToEnd();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        //string s = ex.Message.ToString();
        //        return "{\"Code\":\"404\",\"Msg\":\"" + ex.Message + "\",\"Data\":\"\"}";
        //    }
        //    finally
        //    {
        //        //mutex.ReleaseMutex();
        //    }
        //}
        private string HttpGet(string url,int timeout=4000,string token="")
        {
            //try
            //{
            //    //mutex.WaitOne();
            //    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            //    request.Timeout = 10000;
            //    request.Method = "GET";
            //    request.Accept = "text/html"; 
            //    request.ContentType = "application/json";
            //    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            //    {
            //        return reader.ReadToEnd();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    //string s = ex.Message.ToString();
            //    return "{\"Code\":\"404\",\"Msg\":\"" + ex.Message + "\",\"Data\":\"\"}";
            //}
            //finally
            //{
            //    //mutex.ReleaseMutex();
            //}
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Timeout = timeout;
                request.Method = "GET";
                if (token != "")
                {
                    request.Headers.Add("Authorization", "Bearer " + token);
                }
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                CreateInLog("\n接口报错提示：" + ex.ToString());
                return "{\"Code\":\"404\",\"Msg\":\"{错误\",\"Data\":\"\"}";
            }
        }
        int tag = 0;
        int y = 6;
        private void button4_Click(object sender, EventArgs e)
        {
            CreateParamsList();
        }
        public void CreateParamsList()
        {
            TextBox Key = new TextBox();
            Key.Multiline = true;
            Key.Tag = tag++;
            Key.Width = (int)(paraPanel.Width * 0.4);
            Key.Location = new Point(7, y);
            Key.Parent = paraPanel;
            TextBox Value = new TextBox();
            Value.Multiline = true;
            Value.Tag = tag++;
            Value.Width = (int)(paraPanel.Width * 0.5);
            Value.Location = new Point(Key.Width + 10, y);
            Value.Parent = paraPanel;
            y += 31;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            int count = paraPanel.Controls.Count-1;
            if (count+1==2)
            {
                return;
            }
            paraPanel.Controls.Remove(paraPanel.Controls[count--]);
            paraPanel.Controls.Remove(paraPanel.Controls[count]);
            y -= 31;
        }

        private void reqType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (reqType.SelectedIndex==0)
            {
                actionTxt.Enabled = true;
                nodeNameTxt.Enabled = true;
                nameSpaceTxt.Enabled = true;
            }
            else
            {
                actionTxt.Enabled = false;
                nodeNameTxt.Enabled = false;
                nameSpaceTxt.Enabled = false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string req = reqTxt.Text;
            try
            {
                getNode.Text = SOAPWebServiceTest(urlTxt.Text, req, actionTxt.Text, nodeNameTxt.Text, "http://tempurl.org");
            }
            catch (Exception ex)
            {
                getNode.Text = ex.Message;
            }
        }
        public string SOAPWebServiceTest(string url, string request, string soapAction, string nodeName, string nameSpace = "http://tempurl.org", int time = 5000)
        {
            string method = soapAction.Substring(soapAction.LastIndexOf("/") + 1);
            string req = $@"<?xml version=""1.0"" encoding=""utf-8""?>
                                <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
                                    <soap:Body>
                                        <{method} xmlns=""{nameSpace}"">
                                            {request}
                                        </{method}>
                                    </soap:Body>
                                </soap:Envelope>";
            reqTxt.Text = req;
            //CreateInLog(DateTime.Now + "请求参数条码：" + request);
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Headers.Add("SOAPAction", soapAction);
            webRequest.ContentType = "text/xml;charset=\"utf-8\"";
            webRequest.Timeout = time;
            webRequest.Accept = "text/xml";
            webRequest.Method = "POST";
            //string req = request;
            Stream RequestStream = webRequest.GetRequestStream();
            byte[] bytes = Encoding.UTF8.GetBytes(req);
            RequestStream.Write(bytes, 0, bytes.Length);
            RequestStream.Close();

            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            Stream ResponseStream = response.GetResponseStream();
            //原始数据
            StreamReader sr = new StreamReader(ResponseStream, Encoding.UTF8);
            string result = HttpUtility.HtmlDecode(sr.ReadToEnd());
            resTxt.Text = result;

            //XmlTextReader Reader = new XmlTextReader(ResponseStream);
            //Reader.MoveToContent();
            //string result = HttpUtility.HtmlDecode(Reader.ReadInnerXml());//获取所有的内容节点
            //resTxt.Text = result;
            //XmlDocument xml = new XmlDocument();
            //xml.LoadXml(result);
            //XmlNamespaceManager xmlNamespace = new XmlNamespaceManager(xml.NameTable);
            //xmlNamespace.AddNamespace("ns", nameSpace);
            //XmlNode node = xml.DocumentElement.SelectSingleNode($"//ns:{nodeName}", xmlNamespace);//获取指定节点数据

            //CreateInLog(DateTime.Now + "返回数据：" + result + "\r\n获取节点信息：" + node?.InnerXml);
            //return node?.InnerXml;
            return result;
        }
        static object obj = new object();
        public static void CreateInLog(object logContent)
        {
            lock (obj)
            {
                string filePath = "Log";//路径：如 E:
                filePath = filePath.EndsWith(@"\") ? filePath : (filePath + @"\");
                if (Directory.Exists(filePath) == false)
                {
                    Directory.CreateDirectory(filePath);//判断该路径是否存在，不存在则创建该路径文件夹
                }
                //将日期格式转成yyyyMMdd的格式，如：20170921
                string filename = filePath + "Log接口获取数据_" + DateTime.Now.ToString("yyyyMMdd") + ".txt";//创建文件名 
                StreamWriter sw = null;
                if (File.Exists(filename))
                { sw = new StreamWriter(filename, true, System.Text.Encoding.GetEncoding("UTF-8")); }
                else
                { sw = new StreamWriter(filename, false, System.Text.Encoding.GetEncoding("UTF-8")); }
                StringBuilder dataRow = new StringBuilder();
                dataRow.Append(DateTime.Now.ToString() + "\n" + logContent); sw.WriteLine(dataRow.ToString());//写入内容
                sw.Close();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(resTxt.Text);
            XmlNamespaceManager xmlNamespace = new XmlNamespaceManager(xml.NameTable);
            xmlNamespace.AddNamespace("ns", nameSpaceTxt.Text);
            XmlNode node = xml.DocumentElement.SelectSingleNode($"//ns:{nodeNameTxt.Text}", xmlNamespace);//获取指定节点数据
            getNode.Text = node?.InnerXml;
            LaborderlistClass laborderlist = XmlStrToObject<LaborderlistClass>(getNode.Text);
            dResTxt.Text=JsonConvert.SerializeObject(laborderlist);
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (textBox1.Text=="")
                {
                    return;
                }
                Convert.ToInt32(textBox1.Text);
            }
            catch (Exception)
            {
                textBox1.Text = "1";
            }
        }

        private void rWebServer_CheckedChanged(object sender, EventArgs e)
        {
            if (rWebServer.Checked)
            {
                actionTxt.Enabled = true;
                nodeNameTxt.Enabled = true;
                nameSpaceTxt.Enabled = true;
                comboBox1.Visible = false;
                cbcontentType.Visible = false;
            }
            else
            {
                actionTxt.Enabled = false;
                nodeNameTxt.Enabled = false;
                nameSpaceTxt.Enabled = false;
                comboBox1.Visible = true;
                comboBox1.SelectedIndex = 0;
                cbcontentType.Visible = true;
                cbcontentType.SelectedIndex = 0;
            }
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (textBox2.Text == "")
                {
                    return;
                }
                Convert.ToInt32(textBox2.Text);
            }
            catch (Exception)
            {
                textBox2.Text = "1";
            }
            //if (Convert.ToInt32(textBox2.Text)>1)
            //{
            //    this.Width = 1500;
            //}
            //else
            //{
            //    this.Width = 1215;
            //}
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //MessageBox.Show(e.RowIndex.ToString());
            Form3 form3 = new Form3(e.RowIndex);
            form3.ShowDialog();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> map = new Dictionary<string, string>();
            for (int i = 0; i < paraPanel.Controls.Count; i += 2)
            {
                //map.Add(paraPanel.Controls[i].Text,HttpUtility.HtmlEncode(paraPanel.Controls[i + 1].Text));
                map.Add(paraPanel.Controls[i].Text, $"<![CDATA[{paraPanel.Controls[i + 1].Text}]]>");
            }
            StringBuilder sb = RequestClass.GetRequestStr(nameSpaceTxt.Text, NameTxt.Text, map);
            reqTxt.Text = sb.ToString();
            string req = RequestClass.SOAPRequest(new Uri(urlTxt.Text), sb, nameSpaceTxt.Text, nodeNameTxt.Text);
            getNode.Text = req;
            //string req = @"<return><result><pid /><resultCode>0</resultCode><resultDesc>成功</resultDesc><rhcv_id>0ED75C4D1D298A994BB86F30528C55441BBDD21018D90E3AC17DB92CC41058EA:1</rhcv_id><name>徐春英</name><id_card_type_code>01</id_card_type_code><id_card_value>211421197303103425</id_card_value><qr_type_code /></result></return>";
            Response res= XmlStrToObject<Response>(req);
            MessageBox.Show(res.result.resultCode+":"+res.result.id_card_value);
        }
    }
}
